package com.hh.xx.thrift;

import org.apache.thrift.TException;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;

/**
 * @author tzp
 * @since 2020/5/13
 */
public class CalculatorService implements TCalculator.Iface {
    public static void main(String[] args) {
        try {
            CalculatorService calculatorService = new CalculatorService();
            TCalculator.Processor<CalculatorService> processor = new TCalculator.Processor<>(calculatorService);

            TServerTransport serverTransport = new TServerSocket(9862);
            TServer server = new TSimpleServer(new TServer.Args(serverTransport).processor(processor));

            // Use this for a multithreaded server
            // TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));

            System.out.println("Starting the simple server...");
            server.serve();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void ping() {
        System.out.println("ping()");
    }

    @Override
    public int add(int n1, int n2) {
        System.out.println("add(" + n1 + "," + n2 + ")");
        return n1 + n2;
    }


    @Override
    public int calculate(int logid, TWork work) throws TInvalidOperation, TException {
        System.out.println("calculate(" + logid + ", {" + work.op + "," + work.num1 + "," + work.num2 + "})");
        int val = 0;
        switch (work.op) {
            case ADD:
                val = work.num1 + work.num2;
                break;
            case SUBTRACT:
                val = work.num1 - work.num2;
                break;
            case MULTIPLY:
                val = work.num1 * work.num2;
                break;
            case DIVIDE:
                if (work.num2 == 0) {
                    TInvalidOperation io = new TInvalidOperation();
                    io.whatOp = work.op.getValue();
                    io.why = "Cannot divide by 0";
                    throw io;
                }
                val = work.num1 / work.num2;
                break;
            default:
                TInvalidOperation io = new TInvalidOperation();
                io.whatOp = work.op.getValue();
                io.why = "Unknown operation";
                throw io;
        }
        return val;
    }

    @Override
    public void zip() {
        System.out.println("zip()");
    }

}
